<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Media;
use App\Models\News;
use App\Models\NewsCategory;
use App\Models\NewsDetail;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use QL\QueryList;

class NewsController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('新闻');
            $content->description('管理');
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('编辑');
            $content->description('新闻');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {

        return Admin::content(function (Content $content) {
            $content->header('创建');
            $content->description('新闻');
            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(News::class, function (Grid $grid) {

            $grid->model()->orderBy("id", "desc");
            $grid->id('ID')->sortable();

            $grid->media()->name('媒体');

            $grid->title("标题");

            $grid->status('状态')->switch();


            $grid->created_at();
            $grid->updated_at();
        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {

        return Admin::form(News::class, function (Form $form) {

            //dd($form->model()->frist());

            $form->display('id', 'ID');
            /*$form->select('media_id', '所属媒体')->options(function ($id) {
                $media = Media::find($id);
                if ($media) {
                    return [$media->id => $media->name];
                }
            })->ajax(route('admin.get-media'))->setWidth(2);*/

            $form->select('category_id', '所属分类')->options(NewsCategory::selectOptions())->setWidth(4);

            $form->select('media_id', '所属媒体')->options(Media::all()->pluck('name', 'id'))->setWidth(2);
            $form->text('title', '标题');
            $form->textarea('describe', '摘要');
            $form->image('cover', '封面');
            $form->editor('detail.content', '正文')->attribute(['style' => 'height:400px;'])->setPicStyle("!w600");
            $form->switch('status', '状态')->states(News::newsStatus())->default(1);
            $form->switch('is_index', '首页显示')->states(News::newsIsIndex());
            $form->switch('is_hot', '热门')->states(News::newsIsHost());
            $form->number('zan_num', '赞数量');
            $form->number('view_num', '浏览数量');
            $form->text('source_url', '原文链接');
            $form->datetime('created_at', 'Created At');
            $form->datetime('post_date', 'post_data')->default(date("Y-m-d H:i:s", time()));
            $form->display('updated_at', 'Updated At');
        });
    }

    public function collect_create(Request $request)
    {
        //dd($request->all());

        $data = $request->all();
        $content = $data['content'];

        unset($data['content']);

        $news = News::create($data);

        $news->detail()->save(new NewsDetail(['content' => $content]));

        return redirect(admin_url('news/' . $news->id . '/edit'));

    }

    public function collect(Request $request)
    {
        $c_url = $request->input("c_url");
        $c_source = $request->input("c_source");
        $data = null;
        if (!empty($c_url)) {
            switch ($c_source) {
                case 'wx':
                    $client = new \GuzzleHttp\Client();
                    $res = $client->request('get', $c_url);
                    $html = $res->getBody();
                    $html = str_replace("<!--headTrap<body></body><head></head><html></html>-->", "", $html);
                    $data = QueryList::Query($html, [
                        'title' => ['title', 'html'],
                        'post_date' => ['#post-date', 'text'],
                        'cover' => ['#js_content img:eq(3)', 'data-src', '', function ($cover) {
                            return empty($cover) ? "" : $cover;
                        }],
                        'desc' => ['#js_content', 'text'],
                        'content' => ['#js_content', 'text', 'p img iframe', function ($content) {
                            $content = str_replace("data-src", "src", $content);
                            $content = preg_replace('/style=.+?[\'|\"]/i', "", $content);
                            //$content = preg_replace('/<p.+?\>/i', "", $content);
                            $content = preg_replace('/width=[\'|\"].+?[\'|\"]/i', "", $content);
                            $content = preg_replace('/height=[\'|\"].+?[\'|\"]/i', "", $content);
                            $content = preg_replace('/class=.+?[\'|\"]/i', "", $content);
                            $content = preg_replace('/data-.+?=.+?[\'|\"]/i', "", $content);
                            return $content;
                        }],
                    ])->getData(function ($item) {
                        //图片本地化
                        $item['content'] = QueryList::run('DImage', [
                            'content' => $item['content'],
                            'show_url' => config('admin.upload.host'),
                            'style' => '_w600',
                            'image_path' => date('Y-m-d'),
                            'www_root' => storage_path('img')
                        ]);
                        return $item;
                    });
                    $data = $data[0];
                    //dd($data);
                    $data['c_url'] = $c_url;
                    if (empty($data['title'])) {
                        $error = new MessageBag([
                            'title' => '错误提示',
                            'message' => '文章无法采集',
                        ]);
                        return back()->with(compact('error'));
                    }
                    break;
                default:
                    $error = new MessageBag([
                        'title' => '错误提示',
                        'message' => '暂不支持此渠道采集',
                    ]);
                    return back()->with(compact('error'));
                    break;
            }
        }
        return Admin::content(function (Content $content) use ($data, $request) {
            $content->header('采集');
            $content->description('新闻');
            $content->body(function (Row $row) use ($data, $request) {
                $row->column(8,
                    Admin::form(News::class, function (Form $form) use ($data, $request) {
                        $form->tools(function (Form\Tools $tools) {
                            $tools->disableBackButton();
                            $tools->disableListButton();
                        });
                        $form->disableReset();
                        $form->setAction(admin_url('news/collect-create'));
                        $form->select('category_id', '所属分类')->options(NewsCategory::selectOptions())->setWidth(4);
                        $form->select('media_id', '所属媒体')->options(Media::all()->pluck('name', 'id'))->setWidth(2);
                        $form->text('title', '标题')->default($data['title']);
                        $form->textarea('describe', '摘要')->default(mb_substr(strip_tags($data['desc']), 0, 60));
                        $form->text('cover', '封面')->value(empty($data['cover']) ? "" : $data['cover']);
                        $form->editor('content', '正文')->default($data['content'])->attribute(['style' => 'height:400px;'])->setPicStyle("!w600");
                        $form->hidden('status', '状态')->default(0);
                        //$form->switch('is_index', '首页显示')->states(News::newsIsIndex());
                        //$form->switch('is_hot', '热门')->states(News::newsIsHost());

                        $form->number('zan_num', '赞数量');
                        $form->number('view_num', '浏览数量');
                        $form->text('source_url', '原文链接')->default($request->input("c_url"));
                        $form->text('post_date', '发布时间')->default($data['post_date']);
                    })
                );
                $box = new Box('链接采集');
                $box->style('success');
                $form = new \Encore\Admin\Widgets\Form();
                $form->action(admin_url('new-collect'));
                $form->select('c_source', '采集渠道')->options(['wx' => '微信公众号文章']);
                $form->textarea('c_url', '采集链接')->default($request->input("c_url"));
                $box->content($form);
                $row->column(4, $box);
            });
        });
    }
}
